function doTheChat(profile_page){
	$.fn.ajaxChat = function(params){
		var params = $.extend({refresh:1.7},params);
		
		var chat = function (jElt) {
			//jElt is the jQuery object where the function starts
			var chatContainer=jElt.find('.chat');
			var chat=chatContainer.find('div'); // this is div containing the messages
			var writeInput=jElt.find('.writeInput');
			var chooseNickname=$('#nickname').val();
			var user_id=$('#user_id').val();
			var baseElems = document.getElementsByTagName('base');
			var base      = ""
			if(baseElems.length>0) {base = baseElems[0].href;}
	
			// handle the read messages function
			var readMessages = function(){
				$.getJSON(base+"Ajax/doTheChatRead/"+chooseNickname+"/", function(data){
					$.each(data, function(i,msg){
						chat.append('<p><small>(<a href="'+profile_page+'#profile'+msg.user_id+'">'
								+msg.user_id+'&rsaquo;'+msg.nickname +'</a>)</small> '+' &gt; <strong>'+msg.message+'</strong></p>');
					});
				});
				setTimeout(readMessages,params.refresh*1000);
			}
			readMessages();			
			
			// handle the submit message function
			var activateKeyboard = function(){
				writeInput.submit(function(){
					var input = $(this).find(':input');
					var message = input.val();
					
					if ($.trim(message).length > 0) { //need to have something to say !
						input.val('');
						input.blur();
						$.post(base+"Ajax/doTheChatWrite/"+chooseNickname+"/", { 
							message: message }, function(data){
							input.focus();
							if(data) 
								chat.append('<p><small>(<a href="' + profile_page + '#profile' +user_id+'">'
										+user_id+'&rsaquo;'+data.nickname +
										'</a>)</small>' + ' &gt; <strong>' + data.message + '</strong></p>');
						}, 'json');
					}
					return false;
				});
			}			
			activateKeyboard();
		}
				
		return this.each(function(){chat($(this));});		
	};
}
